package dao.impl;

import dao.SellDao;
import dao.domain.Book;
import dao.domain.Client;
import dao.domain.Sell;
import service.BookService;
import service.UserService;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author huangzhiyang
 * @Date 2023/11/7
 * @Description
 */
public class SellDaoImpl extends BaseDaoImpl implements SellDao {
    private static List<Sell> listSell(ResultSet resultSet) throws SQLException {
        List<Sell> sellList = new ArrayList<>();
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String clientAccount = resultSet.getString("client_account");
            int bookNumber = resultSet.getInt("book_number");
            Date orderDate = resultSet.getDate("orderDate");
            Client client = (Client) UserService.selectByAccount("client", clientAccount);
            Book book = BookService.selectById(bookNumber);
            sellList.add(new Sell(id, client, book, orderDate));
        }
        return sellList;
    }

    /**
     * 数据库储存
     *
     * @param sell 订单对象
     */
    @Override
    public void store(Sell sell) throws SQLException {
        String sql = "INSERT INTO sell (client_account, book_number, orderDate) VALUES (?, ?, NOW())";
        Connection connection = super.getConnection();
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, sell.getClient().getAccount());
        statement.setInt(2, sell.getBook().getNumber());
        statement.executeUpdate();
        super.closeAll(connection, statement, null);
    }

    /**
     * 查询所有订单
     */
    @Override
    public List<Sell> listSell() throws SQLException {
        List<Sell> sells;
        Connection connection = super.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT * FROM `sell`");
        System.out.println("run");
        ResultSet resultSet = statement.executeQuery();
        sells = listSell(resultSet);
        return sells;
    }
}
